$(document).ready(function() {
    //1.初始化Table
    var attenTable = new attentions();
    attenTable.Init();

    var shopTable = new shop();
    shopTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    // 初始化
    $("#myshop").show();
    $("#mypointer").hide();

    $("#pointer").click(function () {
        $("#tb_attention").bootstrapTable('refresh');
        $("#myshop").hide();
        $("#mypointer").show();
    });

    $("#shop").click(function () {
        $("#tb_shop").bootstrapTable('refresh');
        $("#myshop").show();
        $("#mypointer").hide();
    });

    $("#btn_delete").click(function() {
        var arr = $('#tb_attention').bootstrapTable('getSelections');
        var ids = '';
        if(arr.length>0){
            for(var i = 0; i < arr.length; i++) {
                if(i != (arr.length - 1)) {
                    ids += arr[i].id + ',';
                } else {
                    ids += arr[i].id;
                }
            }
            if(confirm('确定删除此任务吗？')) {
                $.ajax({
                    type: "post",
                    url: '/attention/del.do',
                    data: {
                        ids : ids
                    },
                    /*traditional:true,//这使json格式的字符不会被转码*/
                    cache: false,
                    async : true,
                    dataType: "json",
                    success: function (data) {
                        if(data.status == 0) {
                            $("#tb_attention").bootstrapTable('refresh');
                        } else {
                            alert(data.msg);
                        }
                    },
                    error : function (data){
                        alert(data.msg);
                    }
                });
            }
        }else{
            alert("请选择一条数据");
        }
    });

    cancelAtten = function(obj) {
        $(obj).removeAttr("class");
        $(obj).addClass("glyphicon glyphicon-ok");

        $.ajax({
            type: "post",
            url: '/attention/delAtten.do',
            data: {
                ids : $(obj).attr("id")
            },
            /*traditional:true,//这使json格式的字符不会被转码*/
            cache: false,
            async : true,
            dataType: "json",
            success: function (data) {
                if(data.status == 0) {
                    $("#tb_shop").bootstrapTable('refresh');
                    $("#tb_attention").bootstrapTable('refresh');
                } else {
                    alert(data.msg);
                }
            },
            error : function (data){
                alert(data.msg);
            }
        });
    }

    atten = function(obj) {
        $(obj).removeAttr("class");
        $(obj).addClass("glyphicon glyphicon-remove");

        $.ajax({
            type: "post",
            url: '/attention/add.do',
            data: {
                houseid : $(obj).attr("id")
            },
            /*traditional:true,//这使json格式的字符不会被转码*/
            cache: false,
            async : true,
            dataType: "json",
            success: function (data) {
                if(data.status == 0) {
                    $("#tb_shop").bootstrapTable('refresh');
                } else {
                    alert(data.msg);
                }
            },
            error : function (data){
                alert(data.msg);
            }
        });
    }
    /*$("#attention").click(function() {

     });
     $("#attention_cancel").click(function() {

     });*/
});

var attentions = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_attention').bootstrapTable({
            url: '/attention/list.do',         //请求后台的URL（*）
            queryParams: oTableInit.queryParams,//查询参数，页码和页面大小
            method : "post",
            pagination : true,//开启分页功能
            pageNumber : 1,//初始化加载第一页
            pageSize : 5,//默认每页显示记录条数
            pageList : [5,10,20],//可选每页记录条数，从小写到到(必须)
            sidePagination : "server",//分页方式，服务器端
            striped : true,//显示间隔色
            cache : false,
            uniqueId : "id",//每一行的唯一标识
            height : 350,//高度
            paginationPreText : "上一页",//上一页按钮的样式(按钮上的文本值)
            paginationNextText : "下一页",//
            contentType : "application/x-www-form-urlencoded",
            columns: [{
                checkbox: true,
                visible: true
            }, {
                field: 'houseDes',
                title: '房子描述'
            }, {
                field: 'houseAddr',
                title: '位置'
            }, {
                title: "图片",
                align: 'center',
                valign: 'middle',
                width: 40, // 定义列的宽度，单位为像素px
                height: 40,
                formatter: function (value, row, index) {
                    var img = '<img style="width:40px; height:40px;"  src="' + "http://localhost/" + row.houseImage + '" />';
                    return img
                }
            }, {
                field: 'attentionTime',
                title: '关注时间'
            }, {
                field: 'phone',
                title: '联系人电话'
            }],
            onLoadSuccess: function () {
            },
            onLoadError: function () {
                showTips("数据加载失败！");
            },
            onDblClickRow: function (row, $element) {
                var id = row.ID;
                EditViewById(id, 'view');
            },
            rowStyle: function (row, index) { //设置行的特殊样式
                //这里有5个取值颜色['active', 'success', 'info', 'warning', 'danger'];
                var strclass = "";
                if (index % 2 == 0) {
                    strclass = "info";
                } else {
                    strclass = "success";
                }
                return {classes: strclass}
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            type: 0
        };
        return temp;
    };

    return oTableInit;
};

var shop = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_shop').bootstrapTable({
            url: '/house/customerList.do',         //请求后台的URL（*）
            queryParams: oTableInit.queryParams,//查询参数，页码和页面大小
            method : "post",
            pagination : true,//开启分页功能
            pageNumber : 1,//初始化加载第一页
            pageSize : 4,//默认每页显示记录条数
            pageList : [5,10,20],//可选每页记录条数，从小写到到(必须)
            sidePagination : "server",//分页方式，服务器端
            striped : true,//显示间隔色
            cache : false,
            uniqueId : "id",//每一行的唯一标识
            height : 500,//高度
            paginationPreText : "上一页",//上一页按钮的样式(按钮上的文本值)
            paginationNextText : "下一页",//
            contentType : "application/x-www-form-urlencoded",
            columns: [{
                formatter: function (value, row, index) {
                    if (row.houseOne) {
                        var result = "";
                        result += '<div style="clear: both; margin-top: 20px;">'
                        result += '<img style="width:110px; height:110px; display: inline-block; float: left;"  src="' + "http://localhost/" + row.houseOne.image + '" />';
                        result += '<div style="display: inline-block; float: left; margin-left: 15px;">'
                            + '<p><span>价格</span>' + row.houseOne.price + ' 万元</p>' + '<p><span>面积</span>' + row.houseOne.size + ' 平方</p>' + '<p><span>位置</span>   ' + row.houseOne.city + '  ' + row.houseOne.area + '  ' + row.houseOne.street +'</p>'
                            + '<p><span>联系电话</span>' + row.houseOne.sellerPhone + '</p>' +
                            '</div>';
                        if(row.houseOne.isattention == 1) {
                            result += '<div onclick="cancelAtten(this);" id=' + row.houseOne.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-remove">取消关注</div>'
                        } else {
                            result += '<div onclick="atten(this);" id=' + row.houseOne.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-ok"></span>关注</div>'
                        }
                        result += '</div>'
                        return result;
                    }
                }
            }, {
                formatter: function (value, row, index) {
                    if(row.houseTwo) {
                        var result = "";
                        result += '<div style="clear: both; margin-top: 20px;">'
                        result += '<img style="width:110px; height:110px; display: inline-block; float: left;"  src="' + "http://localhost/" + row.houseTwo.image + '" />';
                        result += '<div style="display: inline-block; float: left; margin-left: 15px;">'
                            + '<p><span>价格</span>' + row.houseTwo.price + ' 万元</p>' + '<p><span>面积</span>' + row.houseTwo.size + ' 平方</p>' + '<p><span>位置</span>   ' + row.houseTwo.city + '  ' + row.houseTwo.area + '  ' + row.houseTwo.street +'</p>'
                            + '<p><span>联系电话</span>' + row.houseTwo.sellerPhone + '</p>' +
                            '</div>';
                        if(row.houseTwo.isattention == 1) {
                            result += '<div onclick="cancelAtten(this);" id=' + row.houseTwo.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-remove">取消关注</div>'
                        } else {
                            result += '<div onclick="atten(this);" id=' + row.houseTwo.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-ok"></span>关注</div>'
                        }
                        result += '</div>'
                        return result;
                    }
                }
            }, {
                formatter: function (value, row, index) {
                    if(row.houseThree) {
                        var result = "";
                        result += '<div style="clear: both; margin-top: 20px;">'
                        result += '<img style="width:110px; height:110px; display: inline-block; float: left;"  src="' + "http://localhost/" + row.houseThree.image + '" />';
                        result += '<div style="display: inline-block; float: left; margin-left: 15px;">'
                            + '<p><span>价格</span>' + row.houseThree.price + ' 万元</p>' + '<p><span>面积</span>' + row.houseThree.size + ' 平方</p>' + '<p><span>位置</span>   ' + row.houseThree.city + '  ' + row.houseThree.area + '  ' + row.houseThree.street +'</p>'
                            + '<p><span>联系电话</span>' + row.houseThree.sellerPhone + '</p>' +
                            '</div>';
                        if(row.houseThree.isattention == 1) {
                            result += '<div onclick="cancelAtten(this);" id=' + row.houseThree.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-remove">取消关注</div>'
                        } else {
                            result += '<div onclick="atten(this);" id=' + row.houseThree.id  + ' style="display: inline-block; float: left; margin-bottom: 2px; margin-left: 15px;"><span id="myattentionIcon" class="glyphicon glyphicon-ok"></span>关注</div>'
                        }
                        result += '</div>'
                        return result;
                    }
                }
            }],
            onLoadSuccess: function () {
            },
            onLoadError: function () {
                showTips("数据加载失败！");
            },
            rowStyle: function (row, index) { //设置行的特殊样式
                //这里有5个取值颜色['active', 'success', 'info', 'warning', 'danger'];
                var strclass = "";
                if (index % 2 == 0) {
                    strclass = "info";
                } else {
                    strclass = "success";
                }
                return {classes: strclass}
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            minPrice: removeAllSpace($("#minPrice").val()),
            maxPrice: removeAllSpace($("#maxPrice").val()),
            minSize: removeAllSpace($("#minSize").val()),
            maxSize: removeAllSpace($("#maxSize").val()),
            city: removeAllSpace($("#city").val()),
            area: removeAllSpace($("#area").val()),
            street: removeAllSpace($("#street").val())

        };
        return temp;
    };

    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        $("#btn_query").click(function() {
            $.ajax({
                type: "post",
                url: '/house/customerList.do',
                data: {
                    minPrice: removeAllSpace($("#minPrice").val()),
                    maxPrice: removeAllSpace($("#maxPrice").val()),
                    minSize: removeAllSpace($("#minSize").val()),
                    maxSize: removeAllSpace($("#maxSize").val()),
                    city: removeAllSpace($("#city").val()),
                    area: removeAllSpace($("#area").val()),
                    street: removeAllSpace($("#street").val())
                },
                cache: false,
                async : true,
                dataType: "json",
                success: function (data) {
                    $("#tb_shop").bootstrapTable('load', data);//主要是要这种写法
                },
                error : function (data){
                    alert("查询失败");
                }
            });
        });
    };

    return oInit;
}

function removeAllSpace(str) {
    return str.replace(/\s+/g, "");
}